package com.example.examoj.controller;

import com.example.examoj.common.CodeInValidException;
import com.example.examoj.common.ProblemNotFoundException;
import com.example.examoj.common.Util;
import com.example.examoj.compile.Answer;
import com.example.examoj.compile.Question;
import com.example.examoj.compile.Task;
import com.example.examoj.dao.Problem;
import com.example.examoj.dao.User;
import com.example.examoj.service.ProblemService;
import com.example.examoj.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

@RestController
public class ProblemController {
    @Autowired
    public ObjectMapper objectMapper;
    @Autowired
    public ProblemService problemService;
    static class isCorrect{
        public int correct;
    }
    static class Accept{
        public int id;
    }
    static class Result{
        public int result;
    }
    static class CompileRequest{
        public int id;
        public String code;
    }
    static class CompileResponse{
        public int error;
        public String reason;
        public String stdout;
    }
    @PostMapping("/compile")
    public void compileProblem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        User user= Util.checkUser(req);
        if (user==null){
            resp.setStatus(403);
            String html="<h3>当前用户未登录</h3>";
            resp.getWriter().write(html);
//                resp.sendRedirect("login.html");
            return;

        }
        CompileResponse compileResponse=new CompileResponse();
        CompileRequest compileRequest=null;
        Problem problem=null;
        try{
            resp.setStatus(200);

            String body=readBody(req);
            compileRequest=objectMapper.readValue(body,CompileRequest.class);
            problem=problemService.selectOne(compileRequest.id);
            if (problem==null){
                throw new ProblemNotFoundException();
            }
            String testCode=problem.getTestCode();
            String requestCode=compileRequest.code;
            String finalCode=mergeCode(requestCode,testCode);
            if (finalCode==null){
                throw new CodeInValidException();
            }
            System.out.println(finalCode);
            Task task=new Task();
            Question question=new Question();
            question.setCode(finalCode);
            Answer answer=task.compileAndRun(question);
            compileResponse.error=answer.getError();
            compileResponse.reason=answer.getReason();
            compileResponse.stdout=answer.getStdout();
        } catch (ProblemNotFoundException e) {
            compileResponse.error=3;
            compileResponse.reason="题目没有找到 id="+compileRequest.id;
        }catch (CodeInValidException e) {
            compileResponse.error=3;
            compileResponse.reason="提交的代码不符合要求";
        }finally {String respString=objectMapper.writeValueAsString(compileResponse);
            resp.getWriter().write(respString);
        }

    }

    private  String mergeCode(String requestCode, String testCode) {
        int pos=requestCode.lastIndexOf("}");
        if (pos==-1){
            return null;
        }
        String string=requestCode.substring(0,pos);
        string+=testCode+"\n}";
        return string;
    }
    @GetMapping("/problem")
    public void getAllproblems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        User user= Util.checkUser(req);
        if (user==null){
            resp.setContentType("text/html; charset=utf-8");
            resp.setStatus(403);
            String html="<h3>当前用户未登录</h3>";
            resp.getWriter().write(html);
            return;
//            resp.sendRedirect("login.html");
//            return;
        }
        resp.setStatus(200);
        String id=req.getParameter("id");
        if (id==null||"".equals(id)){
            List<Problem> list=problemService.selectAll();
            String respString=objectMapper.writeValueAsString(list);
            resp.getWriter().write(respString);
            return;
        }else {
            Problem problem=problemService.selectOne(Integer.parseInt(id));
            String respString=objectMapper.writeValueAsString(problem);
            resp.getWriter().write(respString);
            return;
        }
    }
    @PostMapping("/addProblem")
    public void addProblem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("application/json; charset=utf8");
        String body=readBody(req);
        isCorrect correct=new isCorrect();
        if (body==null){
            resp.setContentType("text/html; charset=utf8");
            String html="<h3>提交的题目有问题，无法新加成功！</h3>";
            resp.getWriter().write(html);
            return;
        }
        Problem problem=objectMapper.readValue(body,Problem.class);
        problemService.insert(problem);
        correct.correct=1;
        String html=objectMapper.writeValueAsString(correct);
        System.out.println("html:   "+html);
        resp.getWriter().write(html);
    }
    @PostMapping("deleteProblem")
    public void deleteProblem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("application/json; charset=utf8");
        String body=readBody(req);
        if (body==null){
            resp.setContentType("text/html; charset=utf8");
            String html="<h3>无法删除成功！</h3>";
            resp.getWriter().write(html);
            return;
        }
        Accept accept=objectMapper.readValue(body,Accept.class);
        problemService.delete(accept.id);
        Result result=new Result();
        result.result=1;
        String html=objectMapper.writeValueAsString(result);
        resp.getWriter().write(html);
    }
    private  String readBody(HttpServletRequest req) throws UnsupportedEncodingException {
        int contentLength=req.getContentLength();
        byte[] bytes=new byte[contentLength];
        try (InputStream inputStream = req.getInputStream()){
            inputStream.read(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(bytes,"utf8");
    }
}
